package com.itheima.reggie.controller;/**
 * 功能描述
 *
 * @author 唯硕
 * @date 2022/09/21  15:13
 */

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 *@ClassName CommonController
 *@Description TODO 文件上传和下载
 *@Author 唯硕
 *@Date 2022/9/21 15:13
 *@Version 1.0
 */
@RestController
@RequestMapping("/common")
public class CommonController {

//    文件路径
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需转存到指定位置，否则本次请求后临时文件会删除

        //获得原始文件名
        String originalFilename = file.getOriginalFilename();
        //获得文件名后缀 .jpg等
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名重复照成覆盖
        String filename = UUID.randomUUID().toString()+suffix;

        //创建一个目录对象
        File dir = new File(basePath);
        //目录是否存在
          if(!dir.exists()){
              //目录不存在，创建
              dir.mkdirs();
          }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(filename);
    }

    @GetMapping("/download")
    public void dowload(String name, HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("imagc/jpeg");
            int length = 0;
            byte[] bytes = new byte[1024];
           while ( (length = fileInputStream.read(bytes))!=-1){
               outputStream.write(bytes,0,length);
               outputStream.flush();
           }
           fileInputStream.close();
           outputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }



    }


}
